package cn.wetcland.urban.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.wetcland.urban.admin.mapper.UtFileUploadMapper;
import cn.wetcland.urban.common.AjaxResponse;
import cn.wetcland.urban.common.MyAssert;
import cn.wetcland.urban.common.vo.UploadImgVO;
import cn.wetcland.urban.generator.domain.UtFileUpload;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ut.uploadPath}")
    private String uploadPath;

    @Resource
    public UtFileUploadMapper fileUploadMapper;

    /**
     * 1.文件保存在服务器，url地址保存在数据库
     * 上传成功之后返回成功保存的url地址
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public AjaxResponse upload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        boolean login = StpUtil.isLogin();
        MyAssert.isTrue(login, "未登录不可上传文件");
        UploadImgVO uploadImgVO = new UploadImgVO();
        ArrayList<UploadImgVO.CustomData> customDataArrayList = new ArrayList<>();
        // 如果目录不存在则创建
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(date);
        File uploadDir = new File(uploadPath + "\\" + format);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        String newPath = uploadPath + "\\" + format;

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String OriginalFilename = file.getOriginalFilename();//获取原文件名
                String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
                //重新随机生成名字
                String filename = UUID.randomUUID() + suffixName;
                File localFile = new File(newPath + "\\" + filename);
                String md5DigestAsHex = "";
                try {
                    // 防止重复上传
                    md5DigestAsHex = DigestUtils.md5DigestAsHex(file.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    UtFileUpload digestFile = fileUploadMapper.selectOne(new QueryWrapper<UtFileUpload>().eq("digest", md5DigestAsHex));
                    UploadImgVO.CustomData customData = new UploadImgVO.CustomData();
                    if (digestFile == null) {
                        file.transferTo(localFile); //把上传的文件保存至本地
                        UtFileUpload utFileUpload = new UtFileUpload();
                        utFileUpload.setDigest(md5DigestAsHex);
                        utFileUpload.setFileName(filename);
                        utFileUpload.setOriginName(OriginalFilename);
                        utFileUpload.setUrl(format + "/" + filename);
                        String type = FileTypeUtil.getType(localFile);
                        utFileUpload.setType(type);
                        fileUploadMapper.insert(utFileUpload);

                        customData.setUrl(format + "/" + filename);
                        customData.setAlt(OriginalFilename);
                        customData.setImgId(utFileUpload.getId());
                        customDataArrayList.add(customData);
                    } else {
                        customData.setUrl(digestFile.getUrl());
                        customData.setAlt(digestFile.getFileName());
                        customData.setImgId(digestFile.getId());
                        customDataArrayList.add(customData);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        uploadImgVO.setData(customDataArrayList);
        uploadImgVO.setErrno(0);
        return AjaxResponse.success(uploadImgVO);
    }

    @ApiOperation("图片预览")
    @GetMapping(value = "/img/{date}/{imgName}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@PathVariable String date, @PathVariable String imgName) throws IOException {
        File file = new File(uploadPath + "/" + date + "/" + imgName);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        inputStream.close();
        return bytes;
    }

    @ApiOperation("图片预览")
    @GetMapping(value = "/imgId/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@PathVariable Long id) throws IOException {
        UtFileUpload tmallFileUpload = fileUploadMapper.selectById(id);
        MyAssert.notNull(tmallFileUpload, "该ID对于图片不存在");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(tmallFileUpload.getCreateTime());
        File file = new File(uploadPath + "/" + format + "/" + tmallFileUpload.getFileName());
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        inputStream.close();
        return bytes;
    }

}
